package org.yan.kangaroo.auth.service.email;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.yan.kangaroo.auth.constant.response.ResponseCodeEnum;
import org.yan.kangaroo.common.client.email.EmailApiService;
import org.yan.kangaroo.common.exception.KangarooBaseException;
import org.yan.kangaroo.common.response.BaseResponseCodeEnum;
import org.yan.kangaroo.common.response.InternalServiceResponseCode;
import org.yan.kangaroo.common.response.Result;
import org.yan.kangaroo.common.util.JsonUtils;
import org.yan.kangaroo.pojo.email.entity.EmailSendRecord;
import org.yan.kangaroo.pojo.email.vo.request.SendEmailRequest;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 邮件发送服务
 *
 * @author wangx
 * @date 11/14/2019 17:15
 */
@Service
@AllArgsConstructor
@Slf4j
public class EmailSendService {
    private final EmailApiService emailApiService;

    private final FreeMarkerConfigurer configuration;


    public void sendLoginVerifyCode(String email, String verifyCode) {
        SendEmailRequest sendEmailRequest = new SendEmailRequest();
        sendEmailRequest.setTos(Collections.singletonList(email));
        sendEmailRequest.setSubject("MCP-登录验证码");
        try {
            Template template = configuration.getConfiguration().getTemplate("email_login_verify_code.html");
            Map<String, Object> params = new HashMap<>(1);
            params.put("verifyCode", verifyCode);
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
            sendEmailRequest.setContent(content);
            sendEmailRequest.setSendAccountId(712481394441326592L);
            sendEmailRequest.setRemark("系统登录验证码");
            Result<EmailSendRecord> emailResult = emailApiService.sendEmail(sendEmailRequest);
            log.info("[sendLoginVerifyCode] result:{}", JsonUtils.getInstance().toJson(emailResult));
            if (!emailResult.getCode().equals(BaseResponseCodeEnum.OK.getCode())) {
                throw new KangarooBaseException(new InternalServiceResponseCode(emailResult.getCode(), emailResult.getMessage()));
            }
        } catch (IOException | TemplateException e) {
            log.error("[sendLoginVerifyCode] error:", e);
            throw new KangarooBaseException(ResponseCodeEnum.LOGIN_VERIFY_CODE_SEND_FAIL);
        }
    }

}
